package io.web.bi.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * DateConverter.
 *
 * @date 2023-07-24
 */
public class DateConverter extends AbstractConverter<Date> {

    // new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    static ThreadLocal<SimpleDateFormat> LOCAL = new ThreadLocal<>();

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            LOCAL.remove();
            LOCAL = null;
        }));
    }

    @Override
    protected Date doConvert(String value) {
        // 2023-07-24 15:04:04
        Date date = null;
        try {
            SimpleDateFormat sdf = LOCAL.get();
            System.out.println("date converter: " + Thread.currentThread().getName());
            if (Objects.isNull(sdf)) {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                LOCAL.set(sdf);
            }
            date = sdf.parse(value);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
